﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace eslib.xml
{
    /// <summary>
    /// xml配置写入器
    /// </summary>
    public class XmlConfigWriter
    {
        string savePath { get; set; }


        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="absloteSavePath">文件绝对路径</param>
        public XmlConfigWriter(string absloteSavePath)
        {
            //路径检查
            string dir = Path.GetDirectoryName(absloteSavePath);
            if (!Directory.Exists(dir)) throw new IOException("保存路径不完整:" + dir);

            this.savePath = absloteSavePath;
        }



        //重构单个XmlConfigItem
        private XmlElement CreateElement(XmlDocument doc, XmlConfigItem item)
        {
            //ID
            XmlElement ele = doc.CreateElement(item.ID);

            //属性
            foreach (var atr in item.Attributes)
            {
                ele.SetAttribute(atr.AttributeName, atr.AttributeValue);
            }

            //值
            XmlNode text = doc.CreateNode(XmlNodeType.Text, "", "");
            text.Value = item.Text;
            ele.AppendChild(text);

            return ele;
        }


        //递归重构整个xml,返回根节点
        private XmlElement ReBuild(XmlDocument doc, XmlConfigItem item)
        {
            //重构自身
            XmlElement ele = CreateElement(doc, item);

            if (item.Children.Count > 0)    //还有子节点，递归
            {
                foreach (var child in item.Children)
                {
                    XmlElement childElement = ReBuild(doc, child);
                    ele.AppendChild(childElement);
                }
            }

            return ele;
        }


        /// <summary>
        /// 写入xml
        /// </summary>
        /// <param name="item"></param>
        public void Write(XmlConfigItem item)
        {
            //重组xmldocument对象
            XmlDocument doc = new XmlDocument();


            //声明部分
            XmlNode dec = doc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            XmlDeclaration declar = (XmlDeclaration)dec;
            declar.Encoding = "utf-8";

            doc.AppendChild(declar);


            //重组内容            
            doc.AppendChild(ReBuild(doc, item));


            //写入
            doc.Save(savePath);
        }
    }
}
